package com.drakulo.hi.gfx;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;

import com.drakulo.hi.gfx.panel.Panel;
import com.drakulo.hi.states.MenuState;

public class MenuButton implements HIGraphicComponent {
	private MenuState parent;
	private Class<? extends Panel> panelClass;
	private String label;
	private int x;
	private int y;

	private boolean hover;
	private boolean selected;

	public MenuButton(MenuState parent, Class<? extends Panel> panelClass, String label, int x,
			int y) {
		this.parent = parent;
		this.panelClass = panelClass;
		this.label = label;
		this.x = x;
		this.y = y;
		this.hover = false;
	}

	@Override
	public boolean mouseIsOnIt(int mouseX, int mouseY) {
		if (mouseX > MenuState.MENU_WIDTH || mouseY < this.y
				|| mouseY > this.y + MenuState.BUTTON_PADDING) {
			return false;
		}
		return true;
	}

	@Override
	public void render(Graphics g) throws SlickException {
		render(g, this.x, this.y);
	}

	@Override
	public void render(Graphics g, int x, int y) throws SlickException {
		UnicodeFont font = null;
		if (this.hover || this.selected) {
			font = FontFactory.getMenuButtonFontHover();
		} else {
			font = FontFactory.getMenuButtonFont();
		}
		font.drawString(x, y, this.label);
	}

	public void select() {
		this.selected = true;
	}

	public void unSelect() {
		this.selected = false;
	}

	@Override
	public void update(Input input) {
		if (mouseIsOnIt(input.getMouseX(), input.getMouseY())) {
			this.hover = true;
			if (input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
				this.parent.unSelectAllButtons();
				select();

				Panel p = null;
				try {
					p = this.panelClass.newInstance();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				this.parent.setPanel(p);
			}
		} else {
			this.hover = false;
		}
	}

}
